﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.UserCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.UserHandler
{
    public class UpdUserHandler : IRequestHandler<UpdUserCommand, APIResult<object>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IMapper mapper;

        public UpdUserHandler(IBaseRepository<User> userRep, IMapper mapper)
        {
            this.userRep = userRep;
            this.mapper = mapper;
        }
        public Task<APIResult<object>> Handle(UpdUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var user = userRep.GetAll().Where(x => x.Name == request.Name).Count();
            if (user < 0)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "名称不得重复";
            }
            else
            {
                var a = mapper.Map<User>(request);
                var now = DateTime.Now;
                a.UpdateUser = "admin";
                a.UpdateTime = now;
                var u = userRep.UpdateAsync(a).Result;
                
                result.Code = APIEnum.Success;
                result.Msg = "修改成功";
                result.Data = u;
               
            }
            return Task.FromResult(result);
        }
    }
}
